﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TomNet.Extensions;

namespace TomNet.Core
{
    /// <summary>
    /// 配置文件读取器
    /// </summary>
    public static class SettingsReader
    {
        private static IConfiguration _configuration;
        /// <summary>
        /// 配置文件读取器
        /// </summary>
        public static T LoadSetting<T>(string path) where T : class, new()
        {
            LoadSetting(path);
            var t = System.Activator.CreateInstance<T>();
            _configuration.Bind(t);
            return t;
        }
        /// <summary>
        /// 配置文件读取器
        /// </summary>
        public static void LoadSetting(string path) 
        {
            IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(path, optional: false, reloadOnChange: true);
            _configuration = builder.Build();
        }
        /// <summary>
        /// 读取指定节点信息
        /// </summary>
        /// <param name="key">节点名称，多节点以:分隔</param>
        public static string GetString(string key)
        {
            return _configuration[key];
        }

        /// <summary>
        /// 读取指定节点的简单数据类型的值
        /// </summary>
        /// <param name="key">节点名称，多节点以:分隔</param>
        /// <param name="defaultValue">默认值，读取失败时使用</param>
        public static T GetValue<T>(string key, T defaultValue = default)
        {
            string str = _configuration[key];
            return str.CastTo<T>(defaultValue);
        }
    }
}
